import 'package:flutter/foundation.dart';

/// 帖子类型枚举
enum PostType {
  discussion,  // 讨论
  question,    // 提问
  sharing,     // 分享
  activity,    // 活动
  announcement, // 公告
}

/// 帖子状态枚举
enum PostStatus {
  published,   // 已发布
  draft,       // 草稿
  hidden,      // 隐藏
  deleted,     // 已删除
}

/// 用户等级枚举
enum UserLevel {
  newbie,      // 新手
  regular,     // 普通用户
  active,      // 活跃用户
  expert,      // 专家
  master,      // 大师
}

/// 用户等级扩展
extension UserLevelExtension on UserLevel {
  String get displayName {
    switch (this) {
      case UserLevel.newbie:
        return '新手';
      case UserLevel.regular:
        return '普通用户';
      case UserLevel.active:
        return '活跃用户';
      case UserLevel.expert:
        return '专家';
      case UserLevel.master:
        return '大师';
    }
  }

  String get color {
    switch (this) {
      case UserLevel.newbie:
        return '#9E9E9E';
      case UserLevel.regular:
        return '#2196F3';
      case UserLevel.active:
        return '#4CAF50';
      case UserLevel.expert:
        return '#FF9800';
      case UserLevel.master:
        return '#E91E63';
    }
  }
}

/// 帖子类型扩展
extension PostTypeExtension on PostType {
  String get displayName {
    switch (this) {
      case PostType.discussion:
        return '讨论';
      case PostType.question:
        return '提问';
      case PostType.sharing:
        return '分享';
      case PostType.activity:
        return '活动';
      case PostType.announcement:
        return '公告';
    }
  }

  String get color {
    switch (this) {
      case PostType.discussion:
        return '#2196F3';
      case PostType.question:
        return '#FF9800';
      case PostType.sharing:
        return '#4CAF50';
      case PostType.activity:
        return '#E91E63';
      case PostType.announcement:
        return '#F44336';
    }
  }
}

/// 用户信息类
class User {
  final String id;
  final String username;
  final String avatar;
  final UserLevel level;
  final int points;
  final String bio;
  final DateTime joinDate;
  final bool isVerified;
  final Map<String, dynamic> metadata;

  const User({
    required this.id,
    required this.username,
    this.avatar = '',
    this.level = UserLevel.newbie,
    this.points = 0,
    this.bio = '',
    required this.joinDate,
    this.isVerified = false,
    this.metadata = const {},
  });

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'] ?? '',
      username: json['username'] ?? '',
      avatar: json['avatar'] ?? '',
      level: UserLevel.values.firstWhere(
        (e) => e.name == json['level'],
        orElse: () => UserLevel.newbie,
      ),
      points: json['points'] ?? 0,
      bio: json['bio'] ?? '',
      joinDate: DateTime.parse(json['join_date'] ?? DateTime.now().toIso8601String()),
      isVerified: json['is_verified'] ?? false,
      metadata: Map<String, dynamic>.from(json['metadata'] ?? {}),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'username': username,
      'avatar': avatar,
      'level': level.name,
      'points': points,
      'bio': bio,
      'join_date': joinDate.toIso8601String(),
      'is_verified': isVerified,
      'metadata': metadata,
    };
  }
}

/// 话题类
class Topic {
  final String id;
  final String name;
  final String description;
  final String color;
  final int postCount;
  final int followerCount;
  final bool isFollowing;
  final DateTime createdAt;
  final Map<String, dynamic> metadata;

  const Topic({
    required this.id,
    required this.name,
    this.description = '',
    this.color = '#2196F3',
    this.postCount = 0,
    this.followerCount = 0,
    this.isFollowing = false,
    required this.createdAt,
    this.metadata = const {},
  });

  factory Topic.fromJson(Map<String, dynamic> json) {
    return Topic(
      id: json['id'] ?? '',
      name: json['name'] ?? '',
      description: json['description'] ?? '',
      color: json['color'] ?? '#2196F3',
      postCount: json['post_count'] ?? 0,
      followerCount: json['follower_count'] ?? 0,
      isFollowing: json['is_following'] ?? false,
      createdAt: DateTime.parse(json['created_at'] ?? DateTime.now().toIso8601String()),
      metadata: Map<String, dynamic>.from(json['metadata'] ?? {}),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'description': description,
      'color': color,
      'post_count': postCount,
      'follower_count': followerCount,
      'is_following': isFollowing,
      'created_at': createdAt.toIso8601String(),
      'metadata': metadata,
    };
  }
}

/// 帖子类
class Post {
  final String id;
  final String title;
  final String content;
  final PostType type;
  final PostStatus status;
  final User author;
  final List<String> images;
  final List<Topic> topics;
  final int likeCount;
  final int commentCount;
  final int viewCount;
  final bool isLiked;
  final bool isBookmarked;
  final bool isPinned;
  final DateTime createdAt;
  final DateTime updatedAt;
  final Map<String, dynamic> metadata;

  const Post({
    required this.id,
    required this.title,
    required this.content,
    this.type = PostType.discussion,
    this.status = PostStatus.published,
    required this.author,
    this.images = const [],
    this.topics = const [],
    this.likeCount = 0,
    this.commentCount = 0,
    this.viewCount = 0,
    this.isLiked = false,
    this.isBookmarked = false,
    this.isPinned = false,
    required this.createdAt,
    required this.updatedAt,
    this.metadata = const {},
  });

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'] ?? '',
      title: json['title'] ?? '',
      content: json['content'] ?? '',
      type: PostType.values.firstWhere(
        (e) => e.name == json['type'],
        orElse: () => PostType.discussion,
      ),
      status: PostStatus.values.firstWhere(
        (e) => e.name == json['status'],
        orElse: () => PostStatus.published,
      ),
      author: User.fromJson(json['author'] ?? {}),
      images: List<String>.from(json['images'] ?? []),
      topics: (json['topics'] as List<dynamic>? ?? [])
          .map((item) => Topic.fromJson(item))
          .toList(),
      likeCount: json['like_count'] ?? 0,
      commentCount: json['comment_count'] ?? 0,
      viewCount: json['view_count'] ?? 0,
      isLiked: json['is_liked'] ?? false,
      isBookmarked: json['is_bookmarked'] ?? false,
      isPinned: json['is_pinned'] ?? false,
      createdAt: DateTime.parse(json['created_at'] ?? DateTime.now().toIso8601String()),
      updatedAt: DateTime.parse(json['updated_at'] ?? DateTime.now().toIso8601String()),
      metadata: Map<String, dynamic>.from(json['metadata'] ?? {}),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'content': content,
      'type': type.name,
      'status': status.name,
      'author': author.toJson(),
      'images': images,
      'topics': topics.map((topic) => topic.toJson()).toList(),
      'like_count': likeCount,
      'comment_count': commentCount,
      'view_count': viewCount,
      'is_liked': isLiked,
      'is_bookmarked': isBookmarked,
      'is_pinned': isPinned,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
      'metadata': metadata,
    };
  }

  Post copyWith({
    String? id,
    String? title,
    String? content,
    PostType? type,
    PostStatus? status,
    User? author,
    List<String>? images,
    List<Topic>? topics,
    int? likeCount,
    int? commentCount,
    int? viewCount,
    bool? isLiked,
    bool? isBookmarked,
    bool? isPinned,
    DateTime? createdAt,
    DateTime? updatedAt,
    Map<String, dynamic>? metadata,
  }) {
    return Post(
      id: id ?? this.id,
      title: title ?? this.title,
      content: content ?? this.content,
      type: type ?? this.type,
      status: status ?? this.status,
      author: author ?? this.author,
      images: images ?? this.images,
      topics: topics ?? this.topics,
      likeCount: likeCount ?? this.likeCount,
      commentCount: commentCount ?? this.commentCount,
      viewCount: viewCount ?? this.viewCount,
      isLiked: isLiked ?? this.isLiked,
      isBookmarked: isBookmarked ?? this.isBookmarked,
      isPinned: isPinned ?? this.isPinned,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      metadata: metadata ?? this.metadata,
    );
  }

  /// 获取帖子摘要（截取前100个字符）
  String get summary {
    if (content.length <= 100) return content;
    return '${content.substring(0, 100)}...';
  }

  /// 获取相对时间显示
  String get timeAgo {
    final now = DateTime.now();
    final difference = now.difference(createdAt);
    
    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  /// 检查是否为热门帖子（根据点赞数和评论数）
  bool get isHot {
    return likeCount >= 10 || commentCount >= 5;
  }

  /// 检查是否为新帖子（24小时内）
  bool get isNew {
    final now = DateTime.now();
    return now.difference(createdAt).inHours < 24;
  }
}